package com.heima.wemedia.interceptor;

import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.thread.WmThreadLocalUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.httpclient.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器
 *
 * @Author mr.lin
 * @Date 2025/1/26 17:40
 */
@Component
public class WmTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取token信息
        String token = request.getHeader("token");
        if (token == null) {
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
        //2.获取payload body信息 就是jwt令牌的完整信息
        Claims claims = AppJwtUtil.getClaimsBody(token);
        //3.解析token
        int i = AppJwtUtil.verifyToken(claims);
        //-1：有效，0：有效，1：过期，2：过期
        if (i == 1 || i == 2) {
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
        //4.将用户id存入threadLocal
        Object o = claims.get("id");
        WmUser wmUser = new WmUser();
        wmUser.setId(Integer.parseInt(o.toString()));
        WmThreadLocalUtil.setUser(wmUser);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        WmThreadLocalUtil.clear();
    }
}
